/**
 * @description 持仓查询
 * @author wangjianjun
 */

import React, { PureComponent } from 'react';
import { AdvancedSearch, codeType, DATA_ENTRY, ContentPackage, TabC } from '../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Tabs } from 'antd';
import moment from 'moment';
import style from './index.less';
import _ from 'lodash';
import Bond from './tab/Bond';
import DepositMoney from './tab/DepositMoney';
import DirectFinancing from './tab/DirectFinancing';
import Etf from './tab/Etf';
import ExchangeRepo from './tab/ExchangeRepo';
import ExchangeNegotiatedRepo from './tab/ExchangeNegotiatedRepo';
import InterbankRepo from './tab/InterbankRepo';
import Nonstandard from './tab/Nonstandard';
import OutsideFunds from './tab/OutsideFunds';
import Stock from './tab/Stock';
import BondLending from './tab/BondLending';
import Assets from './tab/Assets';
import OutSourcing from './tab/OutSourcing';
import StockFuture from './tab/StockFuture';
import ShoopFuture from './tab/ShoopFuture';
import NationalFuture from './tab/NationalFuture';
import OptionC from './tab/Option';
import { isZiGuanEvir } from '../../../utils/commonFunc';
import investmentTypeData from '../../../utils/enumeratedValues/investmentType';

const { TabPane } = Tabs;

@Form.create()
export default class PositionInquiry extends PureComponent {
  constructor(props) {
    super(props);
    this.commonArgs = {};
    this.state = {
      activeKey: 'Bond',
      bondArgs: {}, // 债券参数
      outsideFundsArgs: {}, // 场外基金参数
      etfArgs: {}, // ETF参数
      depositMoneyArgs: {}, // 存款参数
      assetplanArgs: {}, // 理财/资产计划参数
      interbankRepoArgs: {}, // 银行间回购参数
      InterbankBuyoutArgs: {}, // 银行间回购参数
      exchangeRepoArgs: {}, // 交易所回购参数
      exchangeNegotiatedRepoArgs: {}, // 交易所协议回购参数
      directFinancingArgs: {}, // 理财直融参数
      nonstandardArgs: {}, // 非标参数
      stockArgs: {}, // 股票参数
      bondLendingArgs: {}, // 债券借贷参数
      assetsArgs: {}, // 资产管理计划参数
      outSourcingArgs: {}, // 委外投资参数
      stockFutureArgs: {}, // 股指期货
      shoopFutureArgs: {}, // 商品期货
      nationalFutureArgs: {}, // 国债期货
      optionArgs: {}, // 期权
      securityType: '', // 选择的证券代码类型
      isZiGuan: false, // 是否资管环境
      HkStkType: '0', // 这个是记录，目前是a股还是h股
    };
  }

  componentWillUnmount() {
    sessionStorage.removeItem('portfolioTracking');
  }

  componentDidUpdate() {
    if (sessionStorage.getItem('portfolioTracking')) {
      const item = JSON.parse(sessionStorage.getItem('portfolioTracking'));
      sessionStorage.removeItem('portfolioTracking');
      this.setState(
        {
          activeKey: item?.activeKey, // 定位tab
        },
        () => {
          const {
            form: { setFieldsValue },
          } = this.formGroupThis.props;
          if (item.exchangeCodeObj) {
            setFieldsValue({ tradingCode: `${item.exchangeCodeObj.exchangeCode}-${item.exchangeCodeObj.tradingCode}` });
            this.commonArgs.exchangeCode = item.exchangeCodeObj ? item.exchangeCodeObj.exchangeCode : this.commonArgs.exchangeCode;
            this.commonArgs.tradingCode = item.exchangeCodeObj ? item.exchangeCodeObj.tradingCode : this.commonArgs.tradingCode;
          } else {
            setFieldsValue({ tradingCode: undefined });
            this.commonArgs.exchangeCode = undefined;
            this.commonArgs.tradingCode = undefined;
          }
          // 判断跳转是否带有日期
          if (item.dataDt) {
            // 改变页面开始时间
            this.state.date?.setDate(moment(item.dataDt));
            this.commonArgs.dataDt = item.dataDt ? item.dataDt : this.commonArgs.dataDt;
          }
          // fundId
          if (item.fundId.some((i) => i !== '')) {
            // componentDidMount内setState异步 走线程执行
            setTimeout(() => {
              this.setState({
                stockArgs: {
                  fundId: item.fundId,
                  dataDt: item.dataDt ? item.dataDt : this.commonArgs.dataDt,
                  timestamp: Number(new Date()),
                  exchangeCode: item.exchangeCodeObj ? item.exchangeCodeObj.exchangeCode : this.commonArgs.exchangeCode,
                  tradingCode: item.exchangeCodeObj ? item.exchangeCodeObj.tradingCode : this.commonArgs.tradingCode,
                },
              });
            }, 0);
            this.state.FormBeanRef?.props?.form?.setFieldsValue({
              fundId: item.fundId,
            });
          }
        },
      );
    }
    if (sessionStorage.getItem('Stock')) {
      sessionStorage.removeItem('Stock');
    }
  }

  componentDidMount() {
    const today = moment().add(0, 'day').format('YYYY-MM-DD');
    const timestamp = new Date().getTime(); // 时间戳,点查询的时候 不管条件有没有改变 都有触发查询
    this.commonArgs = { dataDt: today, timestamp };
    // 如果资管环境页面进入 则定位到etf tab上，并且隐藏其他标签
    if (isZiGuanEvir()) {
      this.setState(
        {
          activeKey: 'Etf',
          isZiGuan: true,
        },
        () => {
          this.getTableData();
        },
      );
    } else {
      this.getTableData();
    }
  }

  componentWillUnmount() {
    if (sessionStorage.getItem('Stock')) {
      sessionStorage.removeItem('Stock');
    }
    sessionStorage.removeItem('portfolioTracking');
  }

  zqCodeChange = (e) => {
    if (e && e.securityType) {
      this.setState({
        securityType: e.securityType,
      });
    } else {
      this.setState({
        securityType: '',
      });
    }
    if (e && e.exchangeCode) {
      if (e.exchangeCode == '162' || e.exchangeCode == '166' || e.exchangeCode == '161') {
        // 此时是港股
        this.setState({
          HkStkType: '1',
        });
      } else if (e.exchangeCode == '101' || e.exchangeCode == '105') {
        // 此时是a股
        this.setState({
          HkStkType: '0',
        });
      }
    } else {
      this.setState({
        HkStkType: '0',
      });
    }
  };

  getTableData = () => {
    const { activeKey, childrenactiveKey } = this.state;
    if (activeKey == 'Bond') {
      this.setState({
        bondArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (childrenactiveKey == 'Etf') {
      this.setState({
        etfArgs: _.cloneDeep(this.commonArgs),
      });
    }

    if (activeKey == 'DepositMoney') {
      this.setState({
        depositMoneyArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (activeKey == 'InterbankRepo') {
      this.setState({
        interbankRepoArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (activeKey == 'InterbankBuyout') {
      this.setState({
        InterbankBuyoutArgs: _.cloneDeep(this.commonArgs),
      });
    }

    if (activeKey == 'DirectFinancing') {
      this.setState({
        directFinancingArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (activeKey == 'Stock') {
      this.setState({
        stockArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (activeKey == 'BondLending') {
      this.setState({
        bondLendingArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (activeKey == 'assets') {
      this.setState({
        assetsArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (activeKey == 'OutSourcing') {
      this.setState({
        outSourcingArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (activeKey == 'StockFuture') {
      this.setState({
        stockFutureArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (childrenactiveKey == 'ShoopFuture') {
      this.setState({
        shoopFutureArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (childrenactiveKey == 'NationalFuture') {
      this.setState({
        nationalFutureArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (childrenactiveKey == 'OutsideFunds') {
      this.setState({
        outsideFundsArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (childrenactiveKey == 'ExchangeRepo') {
      this.setState({
        exchangeRepoArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (childrenactiveKey == 'ExchangeNegotiatedRepo') {
      this.setState({
        exchangeNegotiatedRepoArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (childrenactiveKey == 'Nonstandard') {
      this.setState({
        nonstandardArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (childrenactiveKey == 'option') {
      this.setState({
        optionArgs: _.cloneDeep(this.commonArgs),
      });
    }
  };

  // 父tab切换
  tabOnclick = (e) => {
    this.setState(
      {
        activeKey: e,
        childrenactiveKey: e,
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 子tab切换
  childrentabOnclick = (e) => {
    this.setState(
      {
        childrenactiveKey: e,
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 点击搜索
  getSearchData = (e) => {
    if (sessionStorage.getItem('Stock')) {
      sessionStorage.removeItem('Stock');
    }
    if (e && e.dataDt) {
      e.dataDt = moment(e.dataDt).format('YYYY-MM-DD');
    }
    const timestamp = new Date().getTime(); // 时间戳,点查询的时候 不管条件有没有改变 都有触发查询
    e.timestamp = timestamp;
    this.commonArgs = e;

    let newactiveKey = '';
    if (this.state.securityType == '0') {
      // 债券
      newactiveKey = 'Bond';
    } else if (this.state.securityType == '2') {
      // 场外基金
      newactiveKey = 'OutsideFunds';
    } else if (this.state.securityType == '9') {
      // ETF
      newactiveKey = 'Etf';
    } else if (this.state.securityType == '7') {
      // 理财直融
      newactiveKey = 'DirectFinancing';
    } else if (this.state.securityType == '12') {
      // 非标
      newactiveKey = 'Nonstandard';
    } else if (this.state.securityType == '13' || this.state.securityType == '14') {
      // 交易所协议式回购
      newactiveKey = 'ExchangeNegotiatedRepo';
    } else if (this.state.securityType == '32' || this.state.securityType == '33') {
      // 买断式
      newactiveKey = 'InterbankBuyout';
    } else if (this.state.securityType == '8') {
      // 存款
      newactiveKey = 'DepositMoney';
    } else if (this.state.securityType == '5' || this.state.securityType == '6') {
      // 交易所回购
      newactiveKey = 'ExchangeRepo';
    } else if (this.state.securityType == '3' || this.state.securityType == '4') {
      // 银行间回购
      newactiveKey = 'InterbankRepo';
    } else if (this.state.securityType == '1' || this.state.securityType == 'gp') {
      // 股票
      newactiveKey = 'Stock';
      sessionStorage.setItem('Stock', this.state.HkStkType);
    } else if (this.state.securityType == '16' || this.state.securityType == '17') {
      // 债券借贷
      newactiveKey = 'BondLending';
    } else if (this.state.securityType == '20') {
      // 资产管理计划维护
      newactiveKey = 'assets';
    } else if (this.state.securityType == '21') {
      // 委外投资
      newactiveKey = 'OutSourcing';
    } else if (this.state.securityType == '23' || this.state.securityType == '24') {
      // 股指期货
      newactiveKey = 'StockFuture';
    } else if (this.state.securityType == '26' || this.state.securityType == '27') {
      // 股指期货
      newactiveKey = 'ShoopFuture';
    } else if (this.state.securityType == '28') {
      // 期权
      newactiveKey = 'option';
    } else if (this.state.securityType == '30' || this.state.securityType == '31') {
      // 国债期货
      newactiveKey = 'NationalFuture';
    }

    if (newactiveKey != '') {
      let parentActiveKey = '';
      switch (newactiveKey) {
        case 'OutsideFunds':
          parentActiveKey = 'Etf';
          break;
        case 'ExchangeRepo':
          parentActiveKey = 'InterbankRepo';
          break;
        case 'ExchangeNegotiatedRepo':
          parentActiveKey = 'InterbankRepo';
          break;
        case 'Nonstandard':
          parentActiveKey = 'DirectFinancing';
          break;
        case 'ShoopFuture':
          parentActiveKey = 'StockFuture';
          break;
        case 'NationalFuture':
          parentActiveKey = 'StockFuture';
          break;
        case 'InterbankBuyout':
          parentActiveKey = 'InterbankRepo';
          break;
        default:
          parentActiveKey = newactiveKey;
      }
      this.setState(
        {
          activeKey: parentActiveKey,
          childrenactiveKey: newactiveKey,
        },
        () => {
          this.setState({
            securityType: '',
          });

          this.getTableData();
        },
      );
    } else {
      this.getTableData();
    }
  };

  // 点击重置
  onClear = (e) => {
    this.setState({
      resetTime: new Date().getTime(), // 用于子组件判断父组件是否点击了重置按钮
      securityType: '0', // 债券 回到初始化对应的tab
    });
    this.commonArgs = {};
  };

  render() {
    const { isZiGuan } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'dataDt',
          title: '日期',
          initialValue: moment().add(0, 'day'),
          allowClear: false,
          type: DATA_ENTRY.SINGLEDATE,
          onRef: (ref) => {
            this.state.date = ref;
          },
        },
        {
          title: '组合',
          type: DATA_ENTRY.PRODUCTGROUPTREE,
          isMultiple: true,
          dataIndex: 'fundId',
          maatApi: true,
          onRef: (ref) => {
            this.state.FormBeanRef = ref;
          },
        },
        {
          dataIndex: 'tradingCode',
          codeType: codeType.positioned,
          type: DATA_ENTRY.SECURITIESCODE,
          onChange: (e) => this.zqCodeChange(e),
          onRef: (ref) => (this.formGroupThis = ref),
        },
        {
          dataIndex: 'investmentType',
          title: '投资类型',
          type: DATA_ENTRY.SELECT,
          allowClear: true,
          dataSource: investmentTypeData,
        },
      ],
      onQuery: (e) => this.getSearchData(e),
      onClear: (e) => this.onClear(e),
    };

    return (
      <ContentPackage
        title='持仓查询'
        contentHtml={
          <div className={style.bondDeviationDetail}>
            <Row>
              <AdvancedSearch {...searchProps} />
            </Row>

            <div style={{ marginTop: '10px' }} className={style.tabsOne}>
              <TabC
                tabSource={[
                  { title: '债券', key: 'Bond', content: <Bond bondArgs={this.state.bondArgs} /> },
                  {
                    title: '基金',
                    key: 'Etf',
                    content: (
                      <TabC
                        type='secondTab'
                        tabSource={[
                          { title: '场内（ETF）基金', key: 'Etf', content: <Etf etfArgs={this.state.etfArgs} /> },
                          {
                            title: '场外基金',
                            key: 'OutsideFunds',
                            content: <OutsideFunds activeKey={this.state.activeKey} resetTime={this.state.resetTime} outsideFundsArgs={this.state.outsideFundsArgs} />,
                          },
                        ]}
                        activeKey={this.state.childrenactiveKey}
                        onChange={this.childrentabOnclick}
                      />
                    ),
                  },
                  {
                    title: '回购',
                    key: 'InterbankRepo',
                    content: (
                      <TabC
                        type='secondTab'
                        tabSource={[
                          { title: '银行间质押式', key: 'InterbankRepo', content: <InterbankRepo interbankRepoArgs={this.state.interbankRepoArgs} /> },
                          { title: '交易所质押式', key: 'ExchangeRepo', content: <ExchangeRepo exchangeRepoArgs={this.state.exchangeRepoArgs} /> },
                          {
                            title: '交易所协议式',
                            key: 'ExchangeNegotiatedRepo',
                            content: <ExchangeNegotiatedRepo exchangeNegotiatedRepoArgs={this.state.exchangeNegotiatedRepoArgs} />,
                          },
                          { title: '银行间买断式', key: 'InterbankBuyout', content: <InterbankRepo interbankRepoArgs={this.state.interbankRepoArgs} InterbankBuyout={true} /> },
                        ]}
                        activeKey={this.state.childrenactiveKey}
                        onChange={this.childrentabOnclick}
                      />
                    ),
                  },
                  { title: '存款', key: 'DepositMoney', content: <DepositMoney depositMoneyArgs={this.state.depositMoneyArgs} /> },
                  { title: '股票', key: 'Stock', content: <Stock stockArgs={this.state.stockArgs} /> },
                  {
                    title: '非标',
                    key: 'DirectFinancing',
                    content: (
                      <TabC
                        type='secondTab'
                        tabSource={[
                          { title: '理财直融', key: 'DirectFinancing', content: <DirectFinancing directFinancingArgs={this.state.directFinancingArgs} /> },
                          { title: '非理财直融', key: 'Nonstandard', content: <Nonstandard nonstandardArgs={this.state.nonstandardArgs} /> },
                        ]}
                        activeKey={this.state.childrenactiveKey}
                        onChange={this.childrentabOnclick}
                      />
                    ),
                  },
                  {
                    title: '资产管理计划',
                    key: 'assets',
                    content: <Assets activeKey={this.state.activeKey} resetTime={this.state.resetTime} assetsArgs={this.state.assetsArgs} />,
                  },
                  {
                    title: '期货',
                    key: 'StockFuture',
                    content: (
                      <TabC
                        type='secondTab'
                        tabSource={[
                          { title: '股指期货', key: 'StockFuture', content: <StockFuture stockFutureArgs={this.state.stockFutureArgs} /> },
                          { title: '商品期货', key: 'ShoopFuture', content: <ShoopFuture shoopFutureArgs={this.state.shoopFutureArgs} /> },
                          { title: '国债期货', key: 'NationalFuture', content: <NationalFuture nationalFutureArgs={this.state.nationalFutureArgs} /> },
                        ]}
                        activeKey={this.state.childrenactiveKey}
                        onChange={this.childrentabOnclick}
                      />
                    ),
                  },
                  { title: '期权', key: 'option', content: <OptionC optionArgs={this.state.optionArgs} /> },
                ]}
                activeKey={this.state.activeKey}
                onChange={this.tabOnclick}
              />
            </div>
          </div>
        }
      />
    );
  }
}
